package main

import (
	"fmt"
	jsoniter "github.com/json-iterator/go"
	"github.com/savsgio/atreugo/v11"
	"io/ioutil"
	"time"
)

type WebFrame struct {
	Id int64
	Name string
	Version string
	Birth time.Time
	Author string
}

func main() {
	config := atreugo.Config{
		Addr: "0.0.0.0:2001",
	}
	server := atreugo.New(config)

	server.GET("/", func(ctx *atreugo.RequestCtx) error {
		return ctx.TextResponse("Hello World")
	})

	server.GET("/echo/{path:*}", func(ctx *atreugo.RequestCtx) error {
		return ctx.TextResponse("Echo message: " + ctx.UserValue("path").(string))
	})

	server.GET("/atreugo/parms", func(ctx *atreugo.RequestCtx) error {
		name :=string(ctx.FormValue("name"))
		fmt.Println(name)
		age := string(ctx.FormValue("age"))
		fmt.Println(age)
		sex := string(ctx.FormValue("sex"))
		fmt.Println(sex)

		return ctx.JSONResponse(map[string]interface{}{"code":200, "message":"成功"})
	})

	server.POST("/atreugo/form", func(ctx *atreugo.RequestCtx) error {
		name := string(ctx.FormValue("name"))
		fmt.Println(name)
		age := string(ctx.FormValue("age"))
		fmt.Println(age)

		return ctx.JSONResponse(map[string]interface{}{"code":200, "message":"成功"})
	})

	server.POST("/atreugo/json", func(ctx *atreugo.RequestCtx) error {
		var wf WebFrame
		wfByte := ctx.PostBody()
		dErr := jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal(wfByte, &wf)
		if dErr != nil{
			return ctx.JSONResponse(map[string]interface{}{"code":500, "message":dErr.Error()})
		}

		fmt.Println("wf：", wf)
		return ctx.JSONResponse(map[string]interface{}{"code":200, "message":"成功"})
	})

	v1 := server.NewGroupPath("/v1")
	v1.GET("/", func(ctx *atreugo.RequestCtx) error {
		return ctx.TextResponse("Hello V1 Group")
	})

	server.Static("/static/testReport", "D:/jmeterTest/report/TestReport202108170410.html")

	server.GET("/testReport/{fileName:*}", func(ctx *atreugo.RequestCtx) error {
		fileName := ctx.UserValue("fileName").(string)
		file, err := ioutil.ReadFile("D:/jmeterTest/report/" + fileName)
		if err != nil {
			return ctx.JSONResponse(map[string]interface{}{"code":500, "message":err.Error()})
		}
		return ctx.HTTPResponseBytes(file, 200)
	})

	if err := server.ListenAndServe(); err != nil {
		panic(err)
	}
}
